<template>
  <div class="ar-container">
    <!-- AR视图区域 -->
    <div class="ar-view" ref="arView">
      <video ref="video" autoplay playsinline class="ar-video"></video>
      <canvas ref="canvas" class="ar-canvas"></canvas>
      
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-overlay">
        <div class="loading"></div>
        <p class="loading-text">正在加载AR模型...</p>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="error-overlay">
        <p class="error-text">{{ error }}</p>
        <button class="btn-primary" @click="retry">重试</button>
      </div>

      <!-- 控制面板 -->
      <div class="ar-controls" v-if="!isLoading && !error">
        <button 
          class="btn-control" 
          @click="toggleCamera"
          :title="isCameraOn ? '关闭摄像头' : '开启摄像头'"
        >
          <i class="icon-camera"></i>
        </button>
        <button 
          class="btn-control" 
          @click="toggleAR"
          :disabled="!isCameraOn"
          :title="isARActive ? '关闭AR' : '开启AR'"
        >
          <i class="icon-ar"></i>
        </button>
        <button 
          class="btn-control" 
          @click="resetView"
          :disabled="!isARActive"
          title="重置视图"
        >
          <i class="icon-reset"></i>
        </button>
      </div>
    </div>

    <!-- 操作提示 -->
    <div class="ar-tips" v-if="isARActive">
      <p>双指缩放 - 调整模型大小</p>
      <p>单指拖动 - 移动模型位置</p>
      <p>双指旋转 - 旋转模型</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as THREE from 'three'
import { ARButton } from 'three/examples/jsm/webxr/ARButton.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'

const props = defineProps({
  modelUrl: {
    type: String,
    required: true
  },
  scale: {
    type: Number,
    default: 1
  }
})

// 状态变量
const video = ref(null)
const canvas = ref(null)
const arView = ref(null)
const isLoading = ref(true)
const error = ref(null)
const isCameraOn = ref(false)
const isARActive = ref(false)

// Three.js 相关变量
let scene, camera, renderer, model
let animationFrameId

// 初始化 Three.js 场景
const initThree = () => {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  
  renderer = new THREE.WebGLRenderer({
    canvas: canvas.value,
    antialias: true,
    alpha: true
  })
  renderer.setSize(window.innerWidth, window.innerHeight)
  renderer.xr.enabled = true

  // 添加光源
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
  scene.add(ambientLight)
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
  directionalLight.position.set(0, 1, 1)
  scene.add(directionalLight)
}

// 加载3D模型
const loadModel = async () => {
  try {
    const loader = new GLTFLoader()
    const gltf = await loader.loadAsync(props.modelUrl)
    model = gltf.scene
    model.scale.set(props.scale, props.scale, props.scale)
    scene.add(model)
    isLoading.value = false
  } catch (err) {
    error.value = '模型加载失败，请重试'
    console.error('模型加载失败:', err)
  }
}

// 启动摄像头
const startCamera = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ 
      video: { 
        facingMode: 'environment',
        width: { ideal: 1920 },
        height: { ideal: 1080 }
      } 
    })
    video.value.srcObject = stream
    isCameraOn.value = true
  } catch (err) {
    error.value = '摄像头访问失败，请检查权限设置'
    console.error('摄像头访问失败:', err)
  }
}

// 停止摄像头
const stopCamera = () => {
  if (video.value?.srcObject) {
    const tracks = video.value.srcObject.getTracks()
    tracks.forEach(track => track.stop())
    video.value.srcObject = null
    isCameraOn.value = false
  }
}

// 切换摄像头状态
const toggleCamera = () => {
  if (isCameraOn.value) {
    stopCamera()
  } else {
    startCamera()
  }
}

// 切换AR状态
const toggleAR = () => {
  if (isARActive.value) {
    stopAR()
  } else {
    startAR()
  }
}

// 启动AR
const startAR = () => {
  if (!renderer.xr.isPresenting) {
    renderer.xr.getSession()?.end()
    const session = renderer.xr.getSession()
    if (session) {
      isARActive.value = true
      animate()
    }
  }
}

// 停止AR
const stopAR = () => {
  if (renderer.xr.isPresenting) {
    renderer.xr.getSession()?.end()
    isARActive.value = false
  }
}

// 重置视图
const resetView = () => {
  if (model) {
    model.position.set(0, 0, 0)
    model.rotation.set(0, 0, 0)
    model.scale.set(props.scale, props.scale, props.scale)
  }
}

// 重试
const retry = () => {
  error.value = null
  isLoading.value = true
  loadModel()
}

// 动画循环
const animate = () => {
  animationFrameId = requestAnimationFrame(animate)
  renderer.render(scene, camera)
}

// 处理窗口大小变化
const handleResize = () => {
  if (camera && renderer) {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
  }
}

// 生命周期钩子
onMounted(async () => {
  if (!navigator.xr) {
    error.value = '您的设备不支持AR功能'
    return
  }

  initThree()
  await loadModel()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  stopCamera()
  stopAR()
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.ar-container {
  @apply relative w-full h-full overflow-hidden;
}

.ar-view {
  @apply relative w-full h-full;
}

.ar-video {
  @apply absolute top-0 left-0 w-full h-full object-cover;
}

.ar-canvas {
  @apply absolute top-0 left-0 w-full h-full;
}

.loading-overlay {
  @apply absolute inset-0 flex flex-col items-center justify-center bg-black bg-opacity-50;
}

.loading-text {
  @apply mt-4 text-white text-lg;
}

.error-overlay {
  @apply absolute inset-0 flex flex-col items-center justify-center bg-black bg-opacity-50;
}

.error-text {
  @apply text-white text-lg mb-4;
}

.ar-controls {
  @apply absolute bottom-8 left-1/2 transform -translate-x-1/2 flex gap-4;
}

.btn-control {
  @apply w-12 h-12 rounded-full bg-white bg-opacity-80 flex items-center justify-center 
         shadow-lg hover:bg-opacity-100 transition-all duration-200;
}

.btn-control:disabled {
  @apply opacity-50 cursor-not-allowed;
}

.ar-tips {
  @apply absolute bottom-24 left-1/2 transform -translate-x-1/2 
         bg-black bg-opacity-70 text-white px-4 py-2 rounded-lg text-sm;
}

.icon-camera,
.icon-ar,
.icon-reset {
  @apply w-6 h-6;
}
</style>